<template>
    <uni-popup @change="popupChange" background-color="#fff" type="bottom" borderRadius="36rpx 36rpx 0 0 " ref="popupRef">
        <view class="content">
            <view class="translate-content">
                <!-- 翻译输入框 -->
                <view class="flex">
                    <textarea
                        v-model="inputValue"
                        auto-height
                        class="textarea"
                        :placeholder="getTranslatePlaceholder"
                        placeholder-style="color:#73a0b5; font-weight: 600; font-size: 40rpx;"
                        confirm-type="search"
                        maxlength="64"
                        :focus="inputAutoFocus"
                        @input="translateResult = {}"
                        @confirm="startTranslating"
                    ></textarea>
                    <view class="clear-btn" v-if="!isEmpty(inputValue)" @click="inputValue = ''">
                        <uni-icons type="clear" :size="30" color="#73a0b5"></uni-icons>
                    </view>
                </view>
                <!-- 翻译结果 -->
                <view class="translate-border-top pt-8 mt-8" v-if="!isEmpty(translateResult) && !isEmpty(inputValue)">
                    <view class="text-24"> {{ translateResult.targetText }} </view>
                    <view class="flex justify-between mt-8">
                        <uni-icons
                            type="sound"
                            size="30"
                            :color="currentPlayType == 2 && currentPlayId == translateResult.id ? '#000' : style.primary"
                            @click="playAudio(translateResult.id, 2)"
                        ></uni-icons>
                        <view class="flex">
                            <uni-icons fontFamily="CustomFont" :size="26" :color="style.primary" @click="copyText(translateResult.targetText)">{{ '&#xe8b0' }}</uni-icons>
                            <view class="pl-6"><uni-icons fontFamily="CustomFont" :size="26" :color="style.primary" @click="fullScreen(translateResult.targetText)">{{ '&#xe622' }}</uni-icons></view>
                        </view>
                    </view>
                </view>
                <!-- 语音手动翻译按钮 -->
                <view class="translate-border-top flex justify-center mt-8" v-if="type == 2 && isEmpty(translateResult) && !isEmpty(inputValue)">
                    <view class="translate-btn" @click="startTranslating">
                        <text class="text-16 pr-5">点击翻译</text>
                        <uni-icons type="arrow-right" :size="30" color="#fff"></uni-icons>
                    </view>
                </view>
            </view>
            <!-- 语言切换 -->
            <view class="flex align-center text-14 py-12 relative px-50" v-if="pageLoad">
                <view class="w-50p text-center">{{ formatLang(useTranslateLangStore().sourceLang) }}</view>
                <image
                    src="@/assets/img/switch.png"
                    class="switch-btn"
                    @click="useTranslateLangStore().switchTranslateLang(useTranslateLangStore().sourceLang, useTranslateLangStore().targetLang)"
                ></image>
                <view class="w-50p text-center">{{ formatLang(useTranslateLangStore().targetLang) }}</view>
            </view>
            <view class="close-btn" :class="{ 'voice-close-btn': type == 2 }" @click="closePopup">收起</view>
            <!-- 语音录制按钮 -->
            <view v-if="type == 2">
                <view class="record-tips" v-if="voiceRecognizeStatus == 2"> 松手 完成 </view>
                <view class="voice-btn" @touchstart="touchStart" @touchend="touchEnd" v-if="voiceRecognizeStatus == 1 || voiceRecognizeStatus == 2">
                    <uni-icons type="mic-filled" :size="30" color="#ff5639"></uni-icons>
                    <text class="pl-5">按住说话</text>
                </view>
                <view class="voice-btn" v-else @click="toast('上个录音正在识别中，请稍后尝试')">
                    <uni-icons type="mic-filled" :size="30" color="#ff5639"></uni-icons>
                    <text class="pl-5">识别中...</text>
                </view>
            </view>
        </view>
    </uni-popup>
</template>

<script setup lang="ts">
import { ref, onMounted, watch, computed } from 'vue';
import { isEmpty, copyText, toast, routerPush } from '@/assets/js/utils';
import { formatLang } from '@/assets/js/utils/filters';
import { useTranslateLangStore } from '@/stores/translateLang';
import { translateText } from '@/api/translate';
import { usePlayAudio } from '@/hooks/usePlayAudio';
import { useVoiceRecognize } from '@/hooks/useVoiceRecognize';
import { useIosPay } from "@/hooks/useIosPay";
import { requestAndroidPermission } from "@/assets/js/utils/permission.js";

import style from '../../assets/css/variables.module.scss';

const pageLoad = ref(false);
onMounted(() => {
    pageLoad.value = true;
    // popupRef.value.open();
});
const emit = defineEmits(['update:modelValue', 'translateSuccess', 'translateFullScreen']);
const props = defineProps({
    modelValue: {
        type: Boolean,
        default: false
    },
    type: {
        //翻译类型，1文字，2语音
        type: Number,
        default: 2
    }
});

//是否支付
const { iosPayFlag, getIosPayFlag } = useIosPay();
//翻译文本内容
const inputValue = ref('');
const translateResult: any = ref({});
//开始翻译
const startTranslating = async () => {
    if (isEmpty(inputValue.value)) {
        return;
    }
    uni.showLoading({
        title: '翻译中',
        mask: true
    });
    let data = {
        sourceLang: useTranslateLangStore().sourceLang,
        targetLang: useTranslateLangStore().targetLang,
        sourceText: inputValue.value,
        type: 1
    };
    let [result, err] = await translateText(data);
    if (result) {
        translateResult.value = result;
        emit('translateSuccess', {});
        uni.hideLoading();
    } else {
        await getIosPayFlag();
        let dialogErrorCode = [20003, 20004];
        // #ifdef MP-WEIXIN
        if (dialogErrorCode.includes(err.code) && iosPayFlag.value) {
            uni.hideLoading();
            uni.showModal({
                title: '提示',
                confirmText: '去购买',
                cancelText: '再看看',
                content: err.message,
                success: function (res) {
                    if (res.confirm) {
                        routerPush('/pages/my/pay?flag=1');
                    }
                }
            });
        } else {
            toast(err.message);
        }
        // #endif
        // #ifndef MP-WEIXIN
        toast(err.message);
        // #endif
        
    }
};

//语音识别相关
const { startVoiceRecognize, endVoiceRecognize, recorderCount, voiceRecognizeStatus, recordAuth } = useVoiceRecognize();
const touchStart = async () => {
    if (voiceRecognizeStatus.value != 1) {
        toast('上个录音正在识别中，请稍后尝试');
        return;
    }
    let [result, err] = await startVoiceRecognize();
    if (result) {
        inputValue.value = result;
        translateResult.value = {};
    } else {
        toast(err ? err : '识别失败，请稍后尝试');
    }
};
const touchEnd = () => {
    endVoiceRecognize();
};

//弹窗实例
const popupRef: any = ref(null);
//输入框是否自动聚焦
const inputAutoFocus = ref(false);
//监听弹窗关闭
watch(
    () => props.modelValue,
    val => {
        if (val) {
            popupRef.value.open();
            if (props.type == 1) {
                setTimeout(() => {
                    inputAutoFocus.value = true;
                }, 400);
            } else if (props.type == 2 && !recordAuth.value) {
                //提前授权解决授权回调录音状态错误问题
                // #ifdef MP-WEIXIN
                uni.authorize({
                    scope: 'scope.record', //这里选择scope.(录音、位置、用户信息...都可以)
                    success() {
                        // 允许授权
                        console.log('已授权');
                        recordAuth.value = true;
                    },
                    fail() {}
                });
                // #endif
                // #ifndef MP-WEIXIN
                requestAndroidPermission('android.permission.RECORD_AUDIO');
                // #endif
            }
        } else {
            inputValue.value = '';
            translateResult.value = {};
            inputAutoFocus.value = false;
        }
    }
);
//监听弹窗显示隐藏
const popupChange = (val: any) => {
    if (!val.show) {
        emit('update:modelValue', false);
    }
};
//播放音频相关
const { currentPlayId, currentPlayType, playAudio } = usePlayAudio();

//根据状态显示输入框提示文字
const getTranslatePlaceholder = computed(() => {
    if (props.type == 1) {
        return '请输入要翻译的文本';
    } else if (voiceRecognizeStatus.value == 1) {
        return '按住下方按钮说话';
    } else if (voiceRecognizeStatus.value == 2) {
        return '正在听...';
    } else if (voiceRecognizeStatus.value == 3) {
        return '识别中...';
    }
});

//关闭弹窗
const closePopup = () => {
    popupRef.value.close();
};

// 全屏翻译相关
const fullScreen = (targetText: string) => {
    emit('translateFullScreen', { targetText });
};
</script>

<style lang="scss" scoped>
.content {
    height: 65vh;
    padding: 32rpx 32rpx 0 32rpx;
    position: relative;
}
.translate-content {
    background: #8bd9f0;
    border-radius: 32rpx;
    padding: 40rpx 32rpx;
    .textarea {
        flex: 1;
        font-size: 40rpx;
        font-weight: bold;
        padding-bottom: 10rpx;
    }
    .clear-btn {
        display: flex;
        margin-left: 15rpx;
        width: 55rpx;
        height: 55rpx;
        // background-color: #fff;
        // border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
    }
    .translate-border-top {
        border-top: 1rpx dashed #6abdda;
    }
    .translate-btn {
        margin-top: 32rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        background: $primary;
        border-radius: 64rpx;
        width: 280rpx;
        height: 80rpx;
        color: #fff;
        // border
        // translate-btn pt-16 flex align-center justify-center
    }
}
.voice-btn {
    width: 340rpx;
    height: 120rpx;
    background-color: #ffdbcf;
    border-radius: 64rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    position: absolute;
    bottom: 100rpx;
    left: calc(50% - 170rpx);
    font-size: 32rpx;
    font-weight: bold;
}

.record-tips {
    position: absolute;
    bottom: 260rpx;
    font-size: 40rpx;
    font-weight: bold;
    display: flex;
    width: 100%;
    left: 0;
    justify-content: center;
}

.close-btn {
    width: 340rpx;
    height: 100rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 64rpx;
    border: 1rpx solid $primary;
    color: $primary;
    position: absolute;
    bottom: 108rpx;
    right: calc(50% - 170rpx);
    font-size: 30rpx;
}
.voice-close-btn {
    border: none;
    width: 180rpx;
    right: calc(50% - 355rpx);
}

.switch-btn {
    width: 40rpx;
    height: 40rpx;
    position: absolute;
    left: calc(50% - 24rpx);
}
.w-50p {
    width: 50%;
}
</style>
